<template>
    <div class="flex-1 h-[300px]  ">
        <div class="flex flex-row justify-between enterList">
            <div>
                <EdSelect v-model="videoParams.deviceFactory" :selectParams="data.payDeviceFactoryParams" style="width: 180px; margin-right: 10px;" ></EdSelect>
                <el-button class="ed-button ed_black-bottom" @click="search()"><svg-icon class="svg-middle" icon-class="search-svg"/>查 询</el-button>
                <el-button class="ed-button ed_white_bottom" @click="reset()"><svg-icon icon-class="reset-svg"/>重 置</el-button>
            </div>
            <div>
                <el-popover placement="bottom" title="" ref="popoverRef" trigger="click">
                    <div slot="">
                        <el-upload class="avatar-uploader" action="" drag accept=".xlsx" :before-upload="beforeAvatarUpload" :http-request="httpRequest" :show-file-list="false">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">
                                <el-link icon="el-icon-download" type="primary" download="安防视频设备导入模板.xlsx" href="/template/安防视频设备导入模板.xlsx">安防视频设备导入模板</el-link>
                            </div>
                        </el-upload>
                    </div>
                    <el-button slot="reference"  class="ed-button ed_white_bottom marginRight8 ed-button36" v-has="'basic:member:import'"><i class="el-icon-download"></i>批量导入</el-button>
                </el-popover>
                <el-button class="ed-button ed_black-bottom ed-button36" @click="addDevice"><svg-icon icon-class="synchronizate"/>新增设备</el-button>
            </div>
        </div>
        <ApiTable :api="api.videoDeviceList" ref="table" :params="videoParams">
            <el-table-column type="index" width="80" label="序号"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="deviceFactory" label="厂家" ></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="deviceName" label="设备名称"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="deviceSn" label="设备序列号" ></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="devicePlace" label="设备地点"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="devicePlayAddr" label="播放地址"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="deviceType" label="设备类型" :formatter="setDeviceType"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="操作" width="150px">
                <template slot-scope="scope">
                    <el-button class="ed-table-bottom ed_black_border" v-has="'basic:project:update'" @click="editVideoConfig(scope.row)">编辑</el-button>
                    <el-button class="ed-table-bottom ed_red_border" v-has="'basic:project:update'" @click="deleteVideoConfig(scope.row)">删除</el-button>
                    <!-- <el-button class="ed-table-bottom ed_blue_border" v-has="'basic:project:update'" @click="editConfig(scope.row)">配置</el-button> -->
                </template>
            </el-table-column>
        </ApiTable>
        <!-- 新增编辑弹框 -->
        <EdDialog ref="videDdialogRef" v-if="data.showVideoConfigure" :title="data.isUpdate ? '编辑设备' : '新增设备'" @close-dialog="closeDialog" @save-dialog="saveDialog">
            <el-form :model="videoDeviceForm"  ref="videoDeviceFormRef" label-position='right' label-width="auto">
                <el-row>
                        <el-col :span="22">
                    <el-form-item label="厂家" prop="deviceFactory" :rules="validate.validates({required:true,msg:'请选择'})" >
                        <EdSelect v-model="videoDeviceForm.deviceFactory" :selectParams="data.payDeviceFactoryParams" style="width:100%" ></EdSelect>
                    </el-form-item>
                </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备名称" prop="deviceName" :rules="validate.validates({required:true,msg:'请输入设备名称'})" >
                            <el-input v-model="videoDeviceForm.deviceName" maxlength="20" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备序列号" prop="deviceSn" :rules="validate.validates({required:false,msg:'请输入设备序列号'})" >
                            <el-input v-model="videoDeviceForm.deviceSn" maxlength="50" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="22">
                        <el-form-item label="ip地址" prop="deviceIp" :rules="validate.validates({required:true,msg:'请输入ip地址'})" >
                            <el-input v-model="videoDeviceForm.deviceIp" maxlength="20" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="端口号" prop="devicePort" :rules="validate.validates({required:true,msg:'请输入端口号'})" >
                            <el-input v-model="videoDeviceForm.devicePort" maxlength="20" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备登录账号" prop="deviceLogin" :rules="validate.validates({required:true,msg:'请输入设备登录账号'})" >
                            <el-input v-model="videoDeviceForm.deviceLogin" maxlength="20" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备登录密码" prop="devicePassword" :rules="validate.validates({required:true,msg:'请输入设备登录密码'})" >
                            <el-input v-model="videoDeviceForm.devicePassword" maxlength="20" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="22">
                        <el-form-item label="设备地点" prop="devicePlace" :rules="validate.validates({required:true,msg:'请输入设备地点'})" >
                            <el-input v-model="videoDeviceForm.devicePlace" maxlength="50" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="播放地址" prop="devicePlayAddr" :rules="validate.validates({required:true,msg:'请输入播放地址'})" >
                            <el-input v-model="videoDeviceForm.devicePlayAddr" maxlength="1000" placeholder="请输入flv直播流地址"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备类型" prop="deviceType" >
                            <EdSelect v-model="videoDeviceForm.deviceType" :selectParams="data.deviceTypeParams" style="width:100%"></EdSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="经纬度" >
                            <el-input style="width:40%" maxlength="20" placeholder="请输入" v-model="videoDeviceForm.longitude"></el-input>&nbsp;&nbsp;<el-input style="width:40%" maxlength="20" v-model="videoDeviceForm.latitude"  placeholder="请输入"></el-input>
                            <span class="colorMainTwo marginLeft8" @click="showMap">
                                <i ><svg-icon icon-class="map-svg" style="width: 24px;height: 24px;"/></i>
                            </span>
                        </el-form-item>
                    </el-col>
                </el-row>  
            </el-form>
        </EdDialog>
        <!-- 配置弹框 -->
        <EdDialog ref="configDdialogRef" v-if="data.showConfigure" title="安防视频配置" @close-dialog="closeConfigDialog" @save-dialog="saveConfigDialog">
            <el-form :model="DeviceForm"  ref="DeviceFormRef" label-position='right' label-width="auto">
                <el-row>
                    <el-col :span="22">
                        <el-form-item label="设备名称" prop="deviceName" :rules="validate.validates({required:true,msg:'请输入设备名称'})" >
                            <el-input v-model="DeviceForm.deviceName" maxlength="20" disabled placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备地点" prop="devicePlace" :rules="validate.validates({required:true,msg:'请输入设备地点'})" >
                            <el-input v-model="DeviceForm.devicePlace"  placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="播放地址" prop="devicePlayAddr" :rules="validate.validates({required:true,msg:'请输入播放地址'})" >
                            <el-input v-model="DeviceForm.devicePlayAddr" placeholder="请输入flv直播流地址"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备类型" prop="deviceType" >
                            <EdSelect v-model="DeviceForm.deviceType" :selectParams="data.deviceTypeParams" style="width:100%"></EdSelect>
                            <!-- <el-input v-model="DeviceForm.deviceType" maxlength="20" placeholder="请输入"></el-input> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="经纬度" >
                            <el-input style="width:40%" placeholder="请输入" v-model="DeviceForm.longitude"></el-input>&nbsp;&nbsp;<el-input style="width:40%" v-model="DeviceForm.latitude"  placeholder="请输入"></el-input>
                            <span class="colorMainTwo marginLeft8" @click="showMap">
                                <i ><svg-icon icon-class="map-svg" style="width: 24px;height: 24px;"/></i>
                                <!-- <span class="marginLeft2 cursorPointer">地图定位</span> -->
                            </span>
                        </el-form-item>
                    </el-col>
                </el-row>  
            </el-form>
        </EdDialog>
        <EdMap ref="edMap" @setAddress="setAddress" :edMapObj="data.edMapObj"></EdMap>
        <ed-confirm-delete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue()"></ed-confirm-delete>
        <el-dialog  width="13%" :visible.sync="data.dialogVisible" :close-on-click-modal="false">
            <el-result icon="success" style="color: #67c23a" title="设备同步成功">
            </el-result>
        </el-dialog>
        <el-dialog  width="13%" :visible.sync="data.errorDdialogVisible" :close-on-click-modal="false">
            <el-result icon="error" style="color: #EE7171" title="设备同步失败">
            </el-result>
        </el-dialog>
    </div>
    </template>
    <script setup lang="ts">
    import EdMap from "src/components/EdMap.vue";
    import EdSelect from 'src/components/EdSelect.vue'
    import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
    import EdDialog from 'src/components/EdDialog.vue'
    import ApiTable from 'src/components/ApiTable.vue'
    import * as api from './api'
    import message from 'src/utils/once-message'
    import store from 'src/store'
    import {getDictByCode} from "src/api/dictionaries";
    import * as validate from 'src/utils/validate'
    import { Village } from "../../../types";
    import { Interface } from "../api";
    import { onActivated, onDeactivated, nextTick, ref, reactive, onMounted } from 'vue'
    
    const props = defineProps<{
        village:Village,
        interface:Interface
    }>()
    const videoParams = reactive({
        villageId:props.village.id,
        villageName:props.village.name,
        orgId:store.getters.vid,
        typeCode:props.interface.code,
        deviceFactory:'',
    })
    // 新增设备参数
    const videoDeviceForm = reactive({
        deviceFactory:'',
        deviceName:'',
        deviceSn:'',
        // deviceIp:'',
        // devicePort:'',
        // deviceLogin:'',
        // devicePassword:'',
        devicePlace:'',
        devicePlayAddr:'',
        deviceType:'',
        longitude:'',
        latitude:'',
        lngLat:[],
        orgId:store.getters.vid,
        villageId:props.village.id,
        villageName:props.village.name,
        dockTypeCode: props.interface.code
    })
    // 配置参数
    const DeviceForm = reactive({
        deviceName:'',
        devicePlace:'',
        devicePlayAddr:'',
        deviceType:'',
        longitude:'',
        latitude:'',
        lngLat:[]
    })
    const table = ref()
    const videDdialogRef = ref()
    const confirmDeleteRef = ref()
    const popoverRef = ref()
    const configDdialogRef = ref()
    const videoDeviceFormRef = ref()
    const edMap = ref()
    const DeviceFormRef = ref()
    
    const data = reactive({
        deviceFactory:'',
        dialogVisible:false,
        errorDdialogVisible:false,
        showVideoConfigure:false,
        confirmRowId:'',
        upFile:'',
        isUpdate:false,
        payDeviceFactoryParams:{
            placeholder:"请选择厂家",
            options: [
                {label:"大华", value:"大华"},
                {label:"海康", value:"海康"}
            ],
            disabled:false
        },
        deviceTypeParams:{
            placeholder:"请选择",
            options: [],
            props: {label:"label", value:"value"}
        },
        showConfigure:false,
        edMapObj:{},
    })

    onMounted(()=>{
        nextTick(() => {
            table.value.load()
        })
        getDictByCode("device_type").then(response => {
            if(response.success) {
                data.deviceTypeParams.options=response.data.items
            }
        })
    })
    // 新增设备弹框
    function addDevice() {
        data.showVideoConfigure = true
        data.isUpdate = false
    }
    
    // 新增设备编辑设备
    function saveDialog(){
        videDdialogRef.value.loading = true
        videoDeviceFormRef.value.validate((valid)=>{
            if(valid){
                let lngLat = []
                lngLat.push(videoDeviceForm.longitude)
                lngLat.push(videoDeviceForm.latitude)
                videoDeviceForm.lngLat = lngLat
                if(data.isUpdate == true){
                    api.editVideoList(videoDeviceForm).then(res=>{
                        if(res.success){
                            message.success({
                                message: '编辑成功！',
                                duration: 2000,
                                center:true
                            });
                            closeDialog()
                            table.value.load()
                        }
                    }).catch(()=>{
                        videDdialogRef.value.loading = false
                    })
                } else if (data.isUpdate == false){
                    api.addVideoList(videoDeviceForm).then(res=>{
                        if(res.success){
                            message.success({
                                message: '新增成功！',
                                duration: 2000,
                                center:true
                            });
                            table.value.load()
                            closeDialog()
                        }
                    }).catch(()=>{
                        videDdialogRef.value.loading = false
                    })
                }
            } else {
                videDdialogRef.value.loading = false
            }
        })

    }
    function closeDialog(){
        Object.assign(videoDeviceForm,{
            deviceFactory:'',
            deviceName:'',
            deviceSn:'',
            // deviceIp:'',
            // devicePort:'',
            // deviceLogin:'',
            // devicePassword:'',
            devicePlace:'',
            devicePlayAddr:'',
            deviceType:'',
            longitude:'',
            latitude:'',
            lngLat:[],
            orgId:store.getters.vid,
            villageId:props.village.id,
            villageName:props.village.name,
            dockTypeCode: props.interface.code,
        })
        videDdialogRef.value.loading = false
        data.showVideoConfigure = false
    }
    
     // 视频配置导入
     function beforeAvatarUpload(file){
        const fileType = file.name.split('.');
        const fileDate = fileType.slice(-1);
        if (['xlsx'].indexOf(fileDate[0]) < 0) {
            message.error('仅支持文件格式：.xlsx');
            return false
        }
        const isLt2M = file.size / 1024 / 1024 < 30;
        if (!isLt2M) {
            message.error('上传文件大小不能超过 30MB!');
        }
        if(isLt2M){
           data.upFile = new FormData();
           data.upFile.append("file",file)
           data.upFile.append("villageId", props.village.id);
           data.upFile.append("villageName", props.village.name);
           data.upFile.append("orgId",store.getters.vid);
           data.upFile.append("orgName",store.getters.orgName)
           data.upFile.append("typeCode",props.interface.code)
        }
        return isLt2M;
    }
    function httpRequest(){
        api.batchImport(data.upFile).then(response => {
            if(response.code == 20000) {
                message.success({
                    message: '导入成功！',
                    duration: 2000,
                    center:true
                });
                table.value.load(1)
            }
            popoverRef.value.doClose()
        }).catch(()=>{
            popoverRef.value.doClose()
        })
    }
    // 查询
    function  search(){
        table.value.load(1)
    }
    // 重置
    function reset(){
        videoParams.deviceFactory = ''; 
        table.value.load(1)
    }
    // 编辑回显的接口跟配置共用一个接口
    function editVideoConfig(row){
        data.isUpdate = true
        api.showVideoList(row.id).then(response=>{
             if(response.success){
                Object.assign(videoDeviceForm,response.data)
                data.showVideoConfigure = true
            }
        })
    }
    function deleteVideoConfig(row){
        data.confirmRowId = row.id;
        confirmDeleteRef.value.open("操作确认","确定删除此项设备？","warning")
    }
    function confirmDeleteTrue(){
       api. deleteVideoList({id: data.confirmRowId}).then(response => {
            if(response.success) {
                message.success({
                    message: '视频配置删除成功！',
                    duration: 2000,
                    center:true
                });
               table.value.load(1)
            }
        })
    }
     // 配置弹框
    function editConfig(row){
        data.showConfigure = true
        DeviceForm.deviceName = row.deviceName,
        data.configId= row.id
        // 点配置回显的接口
        api.showVideoList(row.id).then(res=>{
            if(res.success){
                Object.assign(DeviceForm,res.data)
            }
        })
    }
    // 视频配置取消按钮
    function closeConfigDialog(){
        data.showConfigure = false
        DeviceFormRef.value.resetFields()
        clearDeviceForm()
    }
    // 视频配置新增接口,既能新增又能修改
    function saveConfigDialog(){
        configDdialogRef.value.loading = true
        DeviceFormRef.value.validate((valid)=>{
            if(!valid){
                configDdialogRef.value.loading = false
                return
            }
            let lngLat = []
            lngLat.push(DeviceForm.longitude)
            lngLat.push(DeviceForm.latitude)
            DeviceForm.lngLat = lngLat
            api.editConfig(DeviceForm).then(res=>{
                if(res.success){
                    message.success({
                        message: '配置成功！',
                        duration: 2000,
                        center:true
                    })
                    table.value.load()
                    closeConfigDialog()
                } else {
                    message.error({
                        message: '配置失败！',
                        duration: 2000,
                        center:true
                    })
                    configDdialogRef.value.loading = false
                }
            }).catch(()=>{
                configDdialogRef.value.loading = false
            })
        })
    }

    //视频配置 清空
    function clearDeviceForm(){
        Object.assign(DeviceForm, {
            deviceName:'',
            devicePlace:'',
            devicePlayAddr:'',
            deviceType:'',
            longitude:'',
            latitude:'',
            lngLat:[]
        })
    }
   
    function showMap(){
        edMap.value.showMap()
    }
    function setAddress(data){
        videoDeviceForm.longitude = data.lnglat.lng
        videoDeviceForm.latitude = data.lnglat.lat
    }
    function setDeviceType(row){
        let options = data.deviceTypeParams.options.find(x => x.value == row.deviceType)
        return options ? options.label : row.deviceType
    }
    </script>
    
    <style scoped>
/* .enterList{
    margin-bottom: 15px;
    text-align: right;
} */
.enterList{
    text-align: right;
    padding: 10px;
    height: 56px;
}
:deep(.api-table){
    height: calc(100% - 56px);
    display: flex;
    flex-direction: column;
}
    </style>